package com.gewu.pm.ui.dialog;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppAdapter;
import com.gewu.pm.ui.dialog.bean.SalespersonBean;
import com.gewu.pm.widget.SideBarView;
import com.hjq.base.BaseDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 选择业务员对话框（类似微信通讯录）
 */
public final class SelectSalespersonDialog {

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements BaseDialog.OnShowListener, BaseDialog.OnDismissListener {

        private OnListener mListener;

        private final TextView mCancelView;
        private final TextView mTitleView;
        private final TextView mConfirmView;
        private final EditText mSearchEdit;
        private final RecyclerView mRecyclerView;
        private final SideBarView mSideBarView;
        private final TextView mStickyHeaderView;

        private final SalespersonAdapter mAdapter;

        /** 当前选中的业务员（单选模式） */
        private SalespersonBean mSelectedSalesperson = null;
        /** 是否多选模式 */
        private boolean mMultiSelect = false;

        private final Handler mSearchHandler = new Handler(Looper.getMainLooper());
        private Runnable mSearchRunnable;
        private static final long SEARCH_DELAY = 300;

        public Builder(Context context) {
            super(context);
            setContentView(R.layout.select_salesperson_dialog);
            setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

            mCancelView = findViewById(R.id.tv_salesperson_cancel);
            mTitleView = findViewById(R.id.tv_salesperson_title);
            mConfirmView = findViewById(R.id.tv_salesperson_confirm);
            mSearchEdit = findViewById(R.id.et_salesperson_search);
            mRecyclerView = findViewById(R.id.rv_salesperson_list);
            mSideBarView = findViewById(R.id.sidebar_salesperson);
            mStickyHeaderView = findViewById(R.id.tv_sticky_header);

            setOnClickListener(mCancelView, mConfirmView);

            mTitleView.setText("选择业务员");

            mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            mAdapter = new SalespersonAdapter(getContext(), this);
            mRecyclerView.setAdapter(mAdapter);

            mAdapter.loadTestData();

            setupSearch();
            setupSideBar();
            setupStickyHeader();

            addOnShowListener(this);
            addOnDismissListener(this);
        }

        private void setupSearch() {
            mSearchEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String keyword = s.toString().trim();

                    if (mSearchRunnable != null) {
                        mSearchHandler.removeCallbacks(mSearchRunnable);
                    }

                    mSearchRunnable = () -> mAdapter.filter(keyword);
                    mSearchHandler.postDelayed(mSearchRunnable, SEARCH_DELAY);
                }
            });
        }

        private void setupSideBar() {
            mSideBarView.setOnLetterChangeListener(new SideBarView.OnLetterChangeListener() {
                @Override
                public void onLetterChange(String letter) {
                    int position = mAdapter.getPositionForLetter(letter);
                    if (position != -1) {
                        mRecyclerView.scrollToPosition(position);
                        mStickyHeaderView.setText(letter);
                        mStickyHeaderView.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onLetterTouchEnd() {
                    mSearchHandler.postDelayed(() -> updateStickyHeader(), 500);
                }
            });
        }

        private void setupStickyHeader() {
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    updateStickyHeader();
                }
            });
        }

        /**
         * 更新 Sticky Header（优化：顶部时隐藏）
         */
        private void updateStickyHeader() {
            LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            if (layoutManager == null) return;

            int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
            if (firstVisiblePosition == RecyclerView.NO_POSITION) return;

            // 如果在最顶部（第一个位置），隐藏 Sticky Header
            if (firstVisiblePosition == 0) {
                mStickyHeaderView.setVisibility(View.GONE);
                return;
            }

            SalespersonBean item = mAdapter.getItem(firstVisiblePosition);
            if (item != null && item.isHeader()) {
                // 如果第一个可见项是头部，隐藏 Sticky Header（因为列表中的头部已经可见）
                mStickyHeaderView.setVisibility(View.GONE);
            } else if (item != null) {
                // 显示 Sticky Header
                String letter = item.getLetter();
                mStickyHeaderView.setText(letter);
                mStickyHeaderView.setVisibility(View.VISIBLE);
            }
        }

        /**
         * 选择业务员（单选模式）
         */
        void onSalespersonSelected(SalespersonBean salesperson) {
            mSelectedSalesperson = salesperson;
        }
        
        /**
         * 获取是否多选模式
         */
        boolean isMultiSelect() {
            return mMultiSelect;
        }
        
        /**
         * 设置是否多选模式
         */
        public Builder setMultiSelect(boolean multiSelect) {
            mMultiSelect = multiSelect;
            return this;
        }

        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            int viewId = view.getId();
            if (viewId == R.id.tv_salesperson_cancel) {
                dismiss();
                if (mListener != null) {
                    mListener.onCancel(getDialog());
                }
            } else if (viewId == R.id.tv_salesperson_confirm) {
                if (mMultiSelect) {
                    // 多选模式：收集所有选中的项
                    String result = mAdapter.collectSelected();
                    
                    if (TextUtils.isEmpty(result)) {
                        Toast.makeText(getContext(), "请先选择业务员", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    dismiss();
                    if (mListener != null) {
                        // 多选模式返回用顿号分隔的名称，Bean为null
                        mListener.onSelected(getDialog(), result, null);
                    }
                } else {
                    // 单选模式
                    if (mSelectedSalesperson == null) {
                        Toast.makeText(getContext(), "请先选择业务员", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    dismiss();
                    if (mListener != null) {
                        mListener.onSelected(getDialog(), mSelectedSalesperson.getName(), mSelectedSalesperson);
                    }
                }
            }
        }

        @Override
        public void onShow(BaseDialog dialog) {
        }

        @Override
        public void onDismiss(BaseDialog dialog) {
            if (mSearchRunnable != null) {
                mSearchHandler.removeCallbacks(mSearchRunnable);
                mSearchRunnable = null;
            }
        }
    }

    private static final class SalespersonAdapter extends AppAdapter<SalespersonBean> {

        private static final int TYPE_HEADER = 0;
        private static final int TYPE_ITEM = 1;

        private final Builder mBuilder;
        private final List<SalespersonBean> mAllSalespersons = new ArrayList<>();
        private final List<SalespersonBean> mDisplayList = new ArrayList<>();

        private SalespersonAdapter(Context context, Builder builder) {
            super(context);
            mBuilder = builder;
        }

        void loadTestData() {
            String[] names = {
                "阿明", "安娜", "白云", "蔡徐坤", "池金云", "陈浩南",
                "邓超", "董明珠", "范冰冰", "冯小刚", "高圆圆", "郭富城",
                "韩红", "胡歌", "黄晓明", "黄渤", "姜文", "贾玲",
                "李冰冰", "李连杰", "刘德华", "刘亦菲", "马云", "孟美岐",
                "欧阳娜娜", "彭于晏", "孙菲芸", "孙俪", "王宝强", "吴国立"
            };

            mAllSalespersons.clear();
            for (String name : names) {
                mAllSalespersons.add(new SalespersonBean(name));
            }

            sortByPinyin();
            addHeaders();
            setData(mDisplayList);
        }

        /**
         * 按拼音排序（先按首字母，再按姓名）
         */
        private void sortByPinyin() {
            Collections.sort(mAllSalespersons, new Comparator<SalespersonBean>() {
                @Override
                public int compare(SalespersonBean o1, SalespersonBean o2) {
                    // 先按首字母排序
                    int letterCompare = o1.getLetter().compareTo(o2.getLetter());
                    if (letterCompare != 0) {
                        return letterCompare;
                    }
                    // 首字母相同，再按姓名排序
                    return o1.getName().compareTo(o2.getName());
                }
            });
        }

        private void addHeaders() {
            mDisplayList.clear();

            String currentLetter = "";
            for (SalespersonBean person : mAllSalespersons) {
                String letter = person.getLetter();
                if (!letter.equals(currentLetter)) {
                    SalespersonBean header = new SalespersonBean(letter, true);
                    mDisplayList.add(header);
                    currentLetter = letter;
                }
                mDisplayList.add(person);
            }
        }

        void filter(String keyword) {
            if (TextUtils.isEmpty(keyword)) {
                setData(mDisplayList);
            } else {
                List<SalespersonBean> filteredList = new ArrayList<>();
                for (SalespersonBean person : mAllSalespersons) {
                    if (person.getName().contains(keyword) ||
                            person.getPinyin().toLowerCase().contains(keyword.toLowerCase())) {
                        filteredList.add(person);
                    }
                }
                setData(filteredList);
            }
        }

        int getPositionForLetter(String letter) {
            for (int i = 0; i < getData().size(); i++) {
                SalespersonBean item = getItem(i);
                if (item.isHeader() && item.getLetter().equals(letter)) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public int getItemViewType(int position) {
            SalespersonBean item = getItem(position);
            return item.isHeader() ? TYPE_HEADER : TYPE_ITEM;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType == TYPE_HEADER) {
                return new HeaderViewHolder();
            } else {
                return new ItemViewHolder();
            }
        }

        private final class HeaderViewHolder extends AppAdapter<?>.ViewHolder {
            private final TextView mLetterView;

            private HeaderViewHolder() {
                super(R.layout.salesperson_header_item);
                mLetterView = findViewById(R.id.tv_letter);
            }

            @Override
            public void onBindView(int position) {
                SalespersonBean item = getItem(position);
                mLetterView.setText(item.getLetter());
            }
        }

        private final class ItemViewHolder extends AppAdapter<?>.ViewHolder {
            private final CheckBox mCheckBox;
            private final ImageView mAvatarView;
            private final TextView mNameView;

            private ItemViewHolder() {
                super(R.layout.salesperson_item);
                mCheckBox = findViewById(R.id.cb_salesperson);
                mAvatarView = findViewById(R.id.iv_salesperson_avatar);
                mNameView = findViewById(R.id.tv_salesperson_name);
                getItemView().setOnClickListener(v -> onItemClick(getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                SalespersonBean item = getItem(position);
                mCheckBox.setChecked(item.isSelected());
                mNameView.setText(item.getName());
                mAvatarView.setImageResource(R.mipmap.logo_big_icon);
            }

            private void onItemClick(int position) {
                SalespersonBean selectedBean = getItem(position);

                if (mBuilder.isMultiSelect()) {
                    // 多选模式：切换选中状态
                    selectedBean.setSelected(!selectedBean.isSelected());
                    notifyItemChanged(position);
                } else {
                    // 单选模式：清除其他，选中当前
                    for (SalespersonBean bean : getData()) {
                        if (!bean.isHeader()) {
                            bean.setSelected(false);
                        }
                    }

                    selectedBean.setSelected(true);
                    notifyDataSetChanged();

                    mBuilder.onSalespersonSelected(selectedBean);
                }
            }
        }
        
        /**
         * 收集选中的项（多选模式）
         * @return 用"、"分隔的选中项名称
         */
        String collectSelected() {
            List<String> selectedNames = new ArrayList<>();
            for (SalespersonBean bean : getData()) {
                if (!bean.isHeader() && bean.isSelected()) {
                    selectedNames.add(bean.getName());
                }
            }
            return TextUtils.join("、", selectedNames);
        }
    }

    public interface OnListener {
        void onSelected(BaseDialog dialog, String name, SalespersonBean salesperson);

        default void onCancel(BaseDialog dialog) {
        }
    }
}
